<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>

      <el-alert title="添加商品信息" type="info" show-icon center :closable="false">
      </el-alert>

      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 侧边栏便签要放在form标签内 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px"
        label-position="top">
        <el-tabs v-model="activeIndex" :before-leave="beforeTabsLeave" @tab-click="tabClicked"
          tab-position="left">
          <el-tab-pane label="基本信息" name="0">
            <!-- 然后form表单item要放在 tab-pane里面 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">

              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps"
                @change="handleChange"></el-cascader>

            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTableData" :label="item.attr_name" :key="item.attr_id">

              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(ck_item,ck_index) in item.attr_vals" :label="ck_item"
                  :key="ck_index" border></el-checkbox>

              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片上传地址 -->
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
              :on-success="handleSuccess" list-type="picture" :headers="headerObj">
              <el-button size="small" type="primary">点击上传</el-button>

            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce">
            </quill-editor>

            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>

        </el-tabs>
      </el-form>

    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="" :visible.sync="previewDialogVisible" width="50%">
      <el-image style="width: 100%; height: 100%;" :src="previewPath" fit="contain"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import { log } from 'util'
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      // 添加商品的表单对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 商品分类数组
        goods_cat: [],
        // 图片所在路径
        pics: [],
        // 商品的详情
        goods_introduce: '',
        // 参数数组
        attr: []
      },
      // 校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },

      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      manyTableData: [],
      onlyTableData: [],
      uploadURL: 'http://127.0.0.1:9102/api/private/v1/upload',
      // 图片上传需要设置请求头，图片上传组件使用main.js里面的axios，所以需要另外设置请求头来加上token
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片url
      previewPath: '',
      // 预览图片对话框显示与否
      previewDialogVisible: false
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }

      return null
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类，级联菜单
    async getCateList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }

      this.cateList = res.data
    },

    // 级联菜单选择事件
    handleChange() {
      // console.log(this.addForm.goods_cat)

      // 要求必须选择三级菜单，判断数组长度为3
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },

    // 标签页切换事件 用的element定义的钩子
    beforeTabsLeave(activeName, oldActiveName) {
      // console.log(activeName)
      // console.log(oldActiveName)

      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')

        return false
      }
    },

    // 标签页点击事件
    async tabClicked() {
      // console.log(this.activeIndex)

      // 1 代表动态参数面板
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数失败')
        }

        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })

        this.manyTableData = res.data

        // console.log(this.manyTableData)
      }

      // 2 代表静态属性面板
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败')
        }

        this.onlyTableData = res.data

        // console.log(this.onlyTableData)
      }
    },

    // 上传图片预览事件
    handlePreview() {},
    // 处理移除图片事件
    handleRemove() {},
    // 上传成功后事件
    handleSuccess(res) {
      // console.log(res)

      const picInfo = {
        pic: res.data.tmp_path
      }

      this.addForm.pics.push(picInfo)
    },
    // 图片删除事件
    handleRemove(file) {
      // console.log(file);
      // 1，获取图片临时路径
      // 2，从pics数组中，找到该路径的索引值
      // 3，从数组中删除该路径
      const filePath = file.response.data.tmp_path

      const index = this.addForm.pics.findIndex(value => {
        return value.pic === filePath
      })

      this.addForm.pics.splice(index, 1)
    },

    // 点击文件列表中已上传的文件时的钩子，这里实现预览
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewDialogVisible = true
    },

    // 最后添加全部商品信息到数据库
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的商品信息')
        }

        // 深拷贝addForm
        const form = _.cloneDeep(this.addForm)

        // 处理数据
        form.goods_cat = form.goods_cat.join(',')

        // console.log(this.manyTableData)
        // console.log(this.onlyTableData)

        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newArrInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }

          form.attr.push(newArrInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newArrInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }

          form.attr.push(newArrInfo)
        })

        // console.log(form)

        // 发起添加商品请求
        // 商品的名称必须唯一
        const { data: res } = await this.$http.post('goods', form)

        if (res.meta.status !== 201) {
          // console.log(res);
          return this.$message.error(res.meta.msg)
        }

        this.$message.success(res.meta.msg)
        // console.log(res.data)
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 !important;
  margin: 0 10px 10px 0 !important;
}

.btnAdd {
  margin-top: 15px;
}
</style>